package com.wang.web3;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wang.web3.adapter.BoxAdapter;
import com.wang.web3.base.Constant;
import com.wang.web3.bean.BoxListBean;
import com.wang.web3.bean.ContractBean;
import com.wang.web3.bean.KeyListBean;
import com.wang.web3.bean.TianWallet;
import com.wang.web3.contracts.MagicKeys;
import com.wang.web3.data.service.ICallBackListener;
import com.wang.web3.data.service.impl.ApiServiceImpl;
import com.wang.web3.utils.SPUtils;

import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import rx.functions.Action1;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link OpenBoxFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OpenBoxFragment extends Fragment implements BoxAdapter.PersonHolderListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    //设置需要的矿工费

    MagicKeys magicKeys;
    Credentials credentials;

    TextView mtv1,mtv2,mtv3;
    RecyclerView boxList;
    BoxAdapter boxAdapter;
    Gson gson = new Gson();
    List<BoxListBean.DataBean> lists = new ArrayList<>();
    ContractBean contractBean;

    int mykey = 0;

    public OpenBoxFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment OpenBoxFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OpenBoxFragment newInstance(String param1, String param2) {
        OpenBoxFragment fragment = new OpenBoxFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    Handler handler  = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                //现有道具
                case 0:
                     mtv1.setText( "现有道具 \n 翅膀：" + msg.arg1 + "(个)");
                     mtv2.setText( "相框：" + msg.arg2 + "(个)");
                    break;
                //开箱结果
                case 1:
//                    getPropsCount();
                     mtv3.setText((String)msg.obj);
                    break;
                //钥匙数量
                case 2:
                    mykey = msg.arg1;
                    if (mykey > 0){
                    }
                    break;
            }
            return false;
        }
    }
    );

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_open_box, container, false);
        init();
        initData();
//        getPropsCount();
//        ownerIndexToBoxKey();
        mtv1 = view.findViewById(R.id.mtv1);
        mtv2 = view.findViewById(R.id.mtv2);
        mtv3 = view.findViewById(R.id.mtv3);
        boxList = view.findViewById(R.id.boxList);

        boxList.setLayoutManager(new GridLayoutManager(getActivity(),2));
        boxAdapter = new BoxAdapter(lists,this);
        boxList.setAdapter(boxAdapter);

        return view;
    }

    private void initData() {
        ApiServiceImpl.getInstence().boxList("", new ICallBackListener() {
            @Override
            public void onSuccess(String string) {
                BoxListBean boxListBean = gson.fromJson(string, BoxListBean.class);
                lists.addAll(boxListBean.getData());
                boxAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFaild(String string) {

            }
        });

        ApiServiceImpl.getInstence().keyList("", new ICallBackListener() {
            @Override
            public void onSuccess(String string) {
                KeyListBean keyListBean = gson.fromJson(string, KeyListBean.class);
            }

            @Override
            public void onFaild(String string) {

            }
        });
    }

    //获取道具数量
   /* private void getPropsCount(){

        final RemoteCall<Tuple2<BigInteger, BigInteger>> rm =  randomBox.getPropsCount(Constant.ownAddress);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    rm.observable().flatMap(new Func1<Tuple2<BigInteger, BigInteger>, Observable<?>>() {
                        @Override
                        public Observable<Tuple2<BigInteger, BigInteger>> call(Tuple2<BigInteger, BigInteger> bigInteger) {
                            return Observable.just(bigInteger);
                        }
                    }).subscribe(new Action1<Object>(){
                        @Override
                        public void call(Object o) {
                            Tuple2<BigInteger, BigInteger> ss = (Tuple2<BigInteger, BigInteger>)o;
                            ss.getValue1();
                            ss.getValue2();
                            Message message = Message.obtain();
                            message.what = 0;
                            message.arg1 = ss.getValue1().intValue();
                            message.arg2 = ss.getValue2().intValue();
                            handler.sendMessage(message);
                            Log.e("Tag","ran" + ss);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }*/
    //获取指定人拥有的钥匙
  /*  private void ownerIndexToBoxKey(){

        final RemoteCall<BigInteger> rm =  randomBox.ownerIndexToBoxKey(Constant.ownAddress);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    rm.observable().flatMap(new Func1<BigInteger, Observable<?>>() {
                        @Override
                        public Observable<BigInteger> call(BigInteger bigInteger) {
                            return Observable.just(bigInteger);
                        }
                    }).subscribe(new Action1<Object>(){
                        @Override
                        public void call(Object o) {
                            BigInteger ss = (BigInteger)o;
                            Message message = Message.obtain();
                            message.what = 2;
                            message.arg1 = ss.intValue();
                            handler.sendMessage(message);
                            Log.e("Tag","ran" + ss);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }*/

    //开箱子
    /*private void openbox() {
        BigInteger value;
        //判断有无钥匙
        if (mykey > 0){
             value = Convert.toWei("0.0", Convert.Unit.ETHER).toBigInteger();
            mykey--;
        }else{
             value = Convert.toWei("1.0", Convert.Unit.ETHER).toBigInteger();
        }
        final RemoteCall<TransactionReceipt> rm =  randomBox.openBox(value);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    rm.observable().subscribe(new Action1<Object>(){
                        @Override
                        public void call(Object o) {
                            TransactionReceipt ss = (TransactionReceipt)o;
                            List<RandomBox.OpenBoxEventResponse> list  = randomBox.getOpenBoxEvents(ss);
                            String str = new String(list.get(0).propType);
                            String obj = "propCounts==" + list.get(0).propCount + "\n from===" + list.get(0).from + "\n proptype == " + str;
                            Message message = Message.obtain();
                            message.what = 1;
                            message.obj = obj;
                            handler.sendMessage(message);
                            Log.e("Tag","obj" + obj);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }*/

    private void init() {


        Web3j web3 = Web3jFactory.build(new HttpService(Constant.URL));
        String wallet = (String) SPUtils.get(getActivity(),Constant.WALLETLOCKADDRESS,"");
        String contract = (String) SPUtils.get(getActivity(),Constant.CONTRACTADDRESS,"");
        TianWallet tianWallet = gson.fromJson(wallet, TianWallet.class);
        contractBean = gson.fromJson(contract, ContractBean.class);
        credentials = Credentials.create(tianWallet.getPrivateKey().substring(2));
        if (contractBean!=null && contractBean.getMagicKeys() != null ){
            magicKeys = MagicKeys.load(contractBean.getMagicKeys().get(1).getAddress(),web3,credentials,Constant.GAS_PRICE,Constant.GAS_LIMIT);
        }

    }

    @Override
    public void onPersonItemClicked(View v, MotionEvent event, int position) {
         if (v.getId() == R.id.mOpenBtn){
             try {
                 BigInteger bigInteger = magicKeys.getOpenBoxEthPrice(lists.get(position).getBoxAddress()).sendAsync().get();
//                 TransactionReceipt receipt = magicKeys.openBoxBySendEth(lists.get(position).getBoxAddress(),bigInteger).send();
                 final RemoteCall<TransactionReceipt> rm =  magicKeys.openBoxBySendEth(lists.get(position).getBoxAddress(),bigInteger);
                 new Thread(new Runnable() {
                     @Override
                     public void run() {
                         try {
                             rm.observable().subscribe(new Action1<Object>(){
                                 @Override
                                 public void call(Object o) {
                                     TransactionReceipt ss = (TransactionReceipt)o;
                                     List<MagicKeys.SendKeyToBoxEventResponse> list  = magicKeys.getSendKeyToBoxEvents(ss);
//                                     Message message = Message.obtain();
//                                     message.what = 1;
//                                     message.obj = obj;
//                                     handler.sendMessage(message);
                                     Log.e("Tag","obj" );
                                 }
                             });
                         } catch (Exception e) {
                             e.printStackTrace();
                         }
                     }
                 }).start();

                Toast.makeText(getActivity(),"开箱！！！别急",Toast.LENGTH_SHORT).show();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             } catch (ExecutionException e) {
                 e.printStackTrace();
             }

         }
    }
}
